<template>
  <div>
    <h1>增加分类</h1>
    <Form :model="formItem" :label-width="80" ref="formValidate" :rules="ruleValidate">
      <!-- 一级分类 -->
      <FormItem label="上级分类" prop="level">
        <Select @on-change="getValue" class="addInput">
          <Option
            v-for="item in formItem.select"
            :value="item.cid"
            :key="item.cid"
            >{{ item.title }}
          </Option>
        </Select>
      </FormItem>

      <!-- 新分类的名称 -->
      <FormItem label="分类名称" class="addInput" prop="name">
        <Tooltip content="请输入10位以内中文" placement="right-end">
          <Input v-model="formItem.name" placeholder="请输入需要添加的分类名称" class="addInput" maxlength="10"></Input>
        </Tooltip>
      </FormItem>
      <!-- 提交按钮 -->
      <FormItem>
        <Button type="primary" icon="md-checkbox-outline" @click="addSubmit">提交</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { Admin_classify } from "../../../server/home.js"
import {Adim_classifyAdd} from "../../../server/home.js"

export default {
  data() {
    return {
      formItem: {
        select: [],
        name:'',
        
      },
      levelID:'',
      ruleValidate:{
        name: [
          { required: true, message: '输入的名称不能为空', trigger: 'blur' }
        ],
      }
    };
  },
  methods: {
    // 获取分类数据
    getDate() {
      var than = this;
      Admin_classify().then(res => {
  
        for (var item of res.data) {
          if (item.fid == 0) {
            than.formItem.select.push(item);
          }
        }
      });

    },
    // 点击下拉框
    getValue(val) {
      this.levelID = val;
   
      
    },
    // 点击提交按钮
    addSubmit(){
      const classifyName = this.formItem.name
      const fid = this.levelID
      const reg = /^[\u4e00-\u9fa5]{1,10}$/;
 
      if(classifyName == '' && fid== ''){// 当输入框为空或未选择上级分类无法提交
        this.$Message.warning('请选择上级分类，并输入分类名称');
      }else if(classifyName.match(reg)== null){
        this.$Message.error('您输入的名称不是中文');
      }else{
        Adim_classifyAdd(fid,classifyName).then(res=>{
          if(res.err_code==1000){
            this.$Message.success(res.message);
            // location.reload();
            this.$router.push('/admin/categoryManage')
          }else{
            this.$Message.error(res.message);
          }
        });
      }
      
    }
    
  },

  created() {
    this.getDate();
  },
};
</script>

<style scoped>
.addInput {
  width: 67ex;
}

</style>
